<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Pagination;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\CheckUser;
use backend\models\QueryForm;
use backend\models\DataForm;
use backend\models\ReportForm;
use yii\helpers\Json;
use backend\models\OrderForm;
use backend\models\OrderLogic;
use yii\helpers\ArrayHelper;
use common\models\Employees;
use common\models\Process;
use common\models\User;
use common\models\Department;
use common\models\Customer;
use common\models\Product;

/**
 * Order controller
 */
class OrderController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['datalist', 'checkbarcode', 'checkreport', 'create', 'add', 'getdepart', 'getcustomer', 'getprocess'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /*
    * 录入用户
     */
    public function actionCreate($id=null)
    {
        $model = new OrderForm($id);    
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->addOrUpdate()) {

                return $this->redirect(['order/datalist']);
            }
        }

        return $this->render('create', ['model' => $model]);
    }

    /*
    * 客户检测单列表
     */
    public function actionDatalist()
    {
        $data_form = new DataForm;
        $data = CheckUser::find();
        if ($data_form->load(Yii::$app->request->get()) && $data_form->validate()) {
            $data = $data_form->query();
        }

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => '20']);
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();

        return $this->render('datalist', ['model' => $model, 'pages' => $pages]);
    }

    /*
    * Ajax异步获取检测订单状态
     */
    public function actionCheckbarcode()
    {
        $model = new QueryForm;
        if ($model->load(Yii::$app->request->get()) && $model->validate()) {
            $re = $model->check();
        } else {
            $re = [
                'flag' => false,
                'msg' => '数据加载失败'
            ];
        }

        return JSON::encode($re);
    }

    /*
    * Ajax异步获取检测报告单
     */
    public function actionCheckreport()
    {
        $model = new ReportForm;
        if ($model->load(Yii::$app->request->get()) && $model->validate()) {
            $re = $model->check();
        } else {
            $re = [
                'flag' => false,
                'msg' => '数据加载失败'
            ];
        }

        return JSON::encode($re);
    }

    /*
    * 新增订单
     */
    public function actionAdd()
    {
        $model = new OrderLogic;
        $process = Yii::$app->db->createCommand("SELECT DISTINCT(pcode),name FROM process")->queryAll();
        $process = ArrayHelper::map($process, 'pcode', 'name');
        $employee = Employees::find()->all();
        $employee = ArrayHelper::map($employee, 'id', 'realname');
        $depart = Department::find()->select(['id', 'name'])->asArray()->all();
        $depart = JSON::encode(ArrayHelper::map($depart, 'id', 'name'));
        $customer = Customer::find()->asArray()->all();
        $customer = ArrayHelper::map($customer, 'id', 'username');
        $product = Product::find()->asArray()->all();
        $product = ArrayHelper::map($product, 'id', 'name');
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->add()) {

                return $this->redirect(['order/datalist']);
            }
        }

        return $this->render('add', ['product' => $product, 'customer' => $customer, 'depart' => $depart, 'model' => $model, 'process' => $process, 'employee' => $employee]);
    }

    /*
    * 获取承接部门
     */
    // public function actionGetdepart()
    // {
    //     $pcode = trim(Yii::$app->request->get()['pcode']);
    //     $employee = User::findOne(Yii::$app->user->id)->employee;
    //     if ($employee) {
    //         $dids = $employee->departments;
    //         $depart = [];
    //         foreach($dids as $key => $val){
    //           $undertake = Process::find()->select('undertake_depart')->where(['tran_depart' => $val->id, 'pcode' => $pcode])->asArray()->all();  
    //           foreach($undertake as $xey => $xal){
    //             $department = Department::findOne($xal['undertake_depart']);
    //             $depart[$department->id] = $department->name;
    //           }
    //         }
            
    //         return JSON::encode([
    //                 'flag' => true,
    //                 'data' => $depart
    //             ]);
    //     }

    //     return JSON::encode([
    //             'flag' => false
    //         ]);
    // }
        public function actionGetdepart() {
            $pid = trim(Yii::$app->request->get()['pid']);
            $process = Process::findOne($pid);
            if ($process){
                $did = $process->undertake_depart;
                $employee = Department::findOne($did)->employees;
                $re_arr = [];
                foreach($employee as $key => $val){
                    $re_arr[$key] = [
                        'id' => $val->id,
                        'realname' => $val->realname
                    ];
                }

                return JSON::encode([
                        'flag' => true,
                        'depart' => Department::findOne($did)->name,
                        'employee' => $re_arr
                    ]);
            }

            return JSON::encode([
                    'flag' => false
                ]);
        }

    /*
    * 异步获取客户信息
     */
    public function actionGetcustomer()
    {
        $cid = trim(Yii::$app->request->get()['cid']);
        $customer = Customer::findOne($cid);
        if ($customer) {

            return JSON::encode([
                    'flag' => true,
                    'sex' => ($customer->sex == 'M')?'男':'女',
                    'birthday' => date('Y-m-d', $customer->birthday)
                ]);
        } 

        return JSON::encode([
                'flag' => false
            ]);
    }

    /*
    * 异步获取转接关系
     */
    public function actionGetprocess()
    {
        $pcode = trim(Yii::$app->request->get()['pcode']);
        $process = Process::find()->select('id, tran_depart, undertake_depart')->where(['pcode' => $pcode])->asArray()->all();
        $depart = Department::find()->select(['id', 'name'])->asArray()->all();
        $depart = ArrayHelper::map($depart, 'id', 'name');
        $re_arr = [];

        foreach ($process as $key => $val) {
            $re_arr[$val['id']] = [
                'tran_depart' => $depart[$val['tran_depart']],
                'undertake_depart' => $depart[$val['undertake_depart']]
                ];
        }

        if ($re_arr) {

            return JSON::encode([
                    'flag' => true,
                    'data' => $re_arr
                ]);
        } else {
            return JSON::encode([
                    'flag' => false
                ]);
        }
    }

}    